package com.example.service;

import com.example.entity.SysRole;
import com.example.entity.SysUser;
import com.example.mapper.SysRoleMapper;
import com.example.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JdbcUSerServiceDetail implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username: [{}]", username);
        SysUser sysUser = null;
        // 角色信息集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 1. 根据用户名查询用户信息
        if (username != null) {
            sysUser = sysUserMapper.selectSysUser(username);
            log.error("sysUser: [{}]", sysUser.toString());
            String roleName = "";
            if (sysUser != null) {
        
                List<SysRole> roleList = sysRoleMapper.selectRoleByUser(sysUser.getId());
                log.error("roleList: [{}]", roleList.toString());
                for (SysRole role : roleList) {
                    roleName = role.getRolename();
                    GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleName);
                    authorities.add(authority);
                }
            }
            sysUser.setAuthorities(authorities);
        }
        return sysUser;
    }
    
}
